package com.pocketpets.ui.map;

import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.app.pocketpets.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.pocketpets.globaldata.ItemListClass;
import com.pocketpets.globaldata.LocationData;
import com.pocketpets.model.map.MyLocationManager;
import com.pocketpets.model.map.SpotDbAdapter;
import com.theydream.pocketpets.ARcaught.HoldMeUp;

public class Map extends MapActivity{
	// ================================================================
	// Constant
	// ================================================================
	private double RADIUS=1000.0;

	// ================================================================
	// Fields
	// ================================================================

	private MapView mapView;
	private MyLocationOverlay mLocationOverlay;
	private MapController mapController;
	private LocationManager mLocationManager;
	private List<Overlay> mapOverlays;
	private SpotDbAdapter mDbHelper;
	private Projection projection;
	private GeoPoint topLeft;
	private GeoPoint bottomRight;
	private double topLat;
	private double topLon;
	private double bottomLat;
	private double bottomLon;
	private Context mContext;
	private AttractionLayer attLayer;
	private ProgressDialog dialog;
	private MyLocationManager myLocationManager;
	private AttractionLayer missionLayer; 
	private int mMapOption=1; 

	// ================================================================
	// Inheried methods
	// ================================================================

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchmap);
		
		Button btnAR=(Button) findViewById(R.id.btnToAR);
		btnAR.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				startActivity(new Intent(Map.this,HoldMeUp.class));
			}
		});
		Button btnSwitchMap = (Button) findViewById(R.id.btnSwtichMap);
		btnSwitchMap.setOnClickListener(new OnClickListener()
		{
			public void onClick(View v)
			{
				switch (mMapOption)
				{
					case 1:
					{
						mapOverlays.remove(attLayer);
						mMapOption++;
						break;
					}
					case 2:
					{
						mapOverlays.remove(missionLayer);
						mapOverlays.add(attLayer);
						mMapOption++;
						break;
					}
					case 3:
					{	
						mapOverlays.add(missionLayer);
						mMapOption=1;
						break;
					}
					
				}
				mapView.invalidate();
				
			}
		});
		// Create Google Map View
		mContext=this;
		//Button btnLocateMe=(Button) findViewById(R.id.btnLocateMe);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapController = mapView.getController();
		mapOverlays = mapView.getOverlays();
		initMyLocation();

		
		attLayer = new AttractionLayer(this.getResources().getDrawable(R.drawable.map_marker), this);
		missionLayer=new AttractionLayer(this.getResources().getDrawable(R.drawable.mission),this);
		//getScreenLocation(mapView);
		LoadItemFromDataBaseTask loadItem=new LoadItemFromDataBaseTask();
		loadItem.execute();

//		btnLocateMe.setOnClickListener(new OnClickListener(){
//
//			public void onClick(View arg0) 
//			{
//				
//			}
//	    });
		
		

		mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		//mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0, 0, this);
		myLocationManager= MyLocationManager.getMyLocationManager();
		myLocationManager.setLocationManager(this,mapController, mLocationManager);
		

		// geo fix 114.263949 22.336600
	}


	public void getScreenLocation(MapView mapView) {
		projection = mapView.getProjection();
		topLeft = projection.fromPixels(0, 0);
		bottomRight = projection.fromPixels(mapView.getWidth() - 1,
				mapView.getHeight() - 1);
		topLat = topLeft.getLatitudeE6() / 1E6;
		topLon = topLeft.getLongitudeE6() / 1E6;
		bottomLat = bottomRight.getLatitudeE6() / 1E6;
		bottomLon = bottomRight.getLongitudeE6() / 1E6;
	}


	private void initMyLocation() {
		mLocationOverlay = new MyLocationOverlay(this, mapView);
		mapOverlays.add(mLocationOverlay);
		mLocationOverlay.enableCompass();
		mLocationOverlay.runOnFirstFix(new Runnable() {
			public void run() {
				mapController.animateTo(mLocationOverlay.getMyLocation());
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		mLocationOverlay.enableMyLocation();
		
	}

	@Override
	protected void onPause() {
		super.onPause();
		mLocationOverlay.disableMyLocation();
		
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	
	
	// ================================================================
	// Loading ItemOverlay From Database
	// ================================================================
	class LoadItemFromDataBaseTask extends AsyncTask<Object, Object, Boolean>{
		ProgressDialog dialog;
		
		@Override
		protected void onPreExecute()
		{
			dialog=new ProgressDialog(mContext);
			dialog.setMessage("Loading, Please Wait.....");
			dialog.show();
		}
		@Override
		protected Boolean doInBackground(Object... params) {



			mDbHelper = new SpotDbAdapter(mContext);
	        mDbHelper.open();
	        // Get a cursor to all the locations in the database
	        Cursor spotCursor = mDbHelper.fetchAllSpotinfo();
	        //startManagingCursor(spotCursor);
	        // Move to the first row in the cursor
	        spotCursor.moveToFirst();
	        do{ // for all the rows in the cursor
	        // Get the spot's name, latitude and longitude


	        LocationData itemStruct=new LocationData();
	        itemStruct.setTitle(spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_SPOT)));
	        itemStruct.setLat(spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LATITUDE)));
	        itemStruct.setLng(spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LONGITUDE)));
	        itemStruct.setPic(spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_PIC)));
	        ItemListClass.addToItemList(itemStruct);
	        
//	        	String spot =
//	        spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_SPOT));
//	        double latitude =
//	        spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LATITUDE));
//	        double longitude =
//	        spotCursor.getDouble(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_LONGITUDE));
//	        String coordinates = String.format("Longitude: %1$s\nLatitude: %2$s",longitude, latitude);
//	        String pic=spotCursor.getString(spotCursor.getColumnIndexOrThrow(SpotDbAdapter.KEY_PIC));
	        // Geopoint refers to the location. Need to specify latitude,
	        // longitude in microdegrees
	        if (itemStruct.getPic().equals("mission"))
	        {
	        	 GeoPoint point = new GeoPoint((int)(itemStruct.getLat()*1e+6),(int)(itemStruct.getLng()*1e+6));
	 	        // Create an overlay item for the spot
	 	        AttractionSpot overlayitem = new AttractionSpot(point,itemStruct.getTitle(),itemStruct.getPic(),0);
	 	        Drawable drawable=getResources().getDrawable(getResources().getIdentifier(itemStruct.getPic(),"drawable","com.app.pocketpets"));
	 	        drawable.setBounds(-25, -25	,25, 25);
	 	        overlayitem.setMarker(drawable);
	 	     // Add a proximity alert to the location that the user selected
	 	        myLocationManager.addProximityAlert(itemStruct.getTitle(), (double)(point.getLatitudeE6()/1e6),(double)(point.getLongitudeE6()/1e6));
	 	        // Add the overlay item into the HelloItemizedOverlay for each spot
	 	        missionLayer.addOverlay(overlayitem);
	        }
	        
	        else
	        {
	        	 GeoPoint point = new GeoPoint((int)(itemStruct.getLat()*1e+6),(int)(itemStruct.getLng()*1e+6));
	 	        // Create an overlay item for the spot
	 	        AttractionSpot overlayitem = new AttractionSpot(point,itemStruct.getTitle(),itemStruct.getPic(),0);
	 	        Drawable drawable=getResources().getDrawable(getResources().getIdentifier(itemStruct.getPic(),"drawable","com.app.pocketpets"));
	 	        drawable.setBounds(-25, -25	,25, 25);
	 	        overlayitem.setMarker(drawable);
	 	     // Add a proximity alert to the location that the user selected
	 	        myLocationManager.addProximityAlert(itemStruct.getTitle(), (double)(point.getLatitudeE6()/1e6),(double)(point.getLongitudeE6()/1e6));
	 	        // Add the overlay item into the HelloItemizedOverlay for each spot
	 	        attLayer.addOverlay(overlayitem);
	        }
	       
	       
	     
	        
	     
	        } while (spotCursor.moveToNext());
	     // until you exhaust all the rows. returns false when we reach the end of the cursor
	       
	        spotCursor.close();
	        return true;
		}
		@Override
		protected void onPostExecute(Boolean bo)
		{
			dialog.dismiss();
			mapOverlays.add(attLayer);
			mapOverlays.add(missionLayer);
			mapController.setZoom(18);
			mapController.animateTo(new GeoPoint(22336904 ,114263333));
			mapView.invalidate();
			
		}
		
	}

}
